import os
import time
from selenium.webdriver import ActionChains
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from public.config import log
from selenium.webdriver.common.by import By
from selenium.common.exceptions import NoSuchElementException


class PageMethod:
    """调用方法"""
    def __init__(self, driver):
        self.driver = driver

    def scroll(self):
        self.driver.execute_script('window.scrollTo(0,3280)')

    @staticmethod
    def isdisplayed(element, tid):
        """元素是否存在"""
        try:
            value = element.is_displayed()
            if value:
                log.info('元素{}存在'.format(element), tid)
            else:
                log.info('元素{}不存在'.format(element), tid)
            return value
        except AttributeError as e:
            log.error(e, tid)


    @staticmethod
    def Sleep(secondes):
        """强制等待"""
        time.sleep(secondes)
        log.info('暂停%d秒' % secondes)

    def implicitly_wait(self, seconds):
        """隐式等待"""
        self.driver.implicitly_wait(seconds)
        log.info("隐式等待{}秒".format(seconds))


    def get_img(self, rq=time.strftime('%Y%m%d%H%M', time.localtime(time.time()))):
        """截图"""
        path = os.path.join(os.path.abspath('..'), 'report', 'img')
        # path = os.path.join(getcwd.get_cwd(), 'screenshots/')  # 拼接截图保存路径
        # rq = time.strftime('%Y%m%d%H%M', time.localtime(time.time()))  # 按格式获取当前时间
        screen_name = path + rq + '.png'  # 拼接截图文件名
        # noinspection PyBroadException
        try:
            self.driver.get_screenshot_as_file(screen_name)
            log.info("截图保存成功{}".format(screen_name))
        except BaseException as e:
            log.error("截图失败{}".format(e))

    def find_element(self, by, value, tid):
        """定位元素"""
        element = None
        if by in ['id', 'name', 'class', 'tag', 'link', 'plink', 'css', 'xpath']:
            try:
                if by == 'id':
                    element = self.driver.find_element(By.ID, value)
                    log.debug('元素定位成功。定位方式：%s,使用的值：%s' % (by, value), tid)
                elif by == 'name':
                    element = self.driver.find_element(By.NAME,value)
                    log.debug('元素定位成功。定位方式：%s,使用的值：%s' % (by, value), tid)
                elif by == 'class':
                    element = self.driver.find_element(By.CLASS_NAME,value)
                    log.debug('元素定位成功。定位方式：%s,使用的值：%s' % (by, value), tid)
                elif by == 'tag':
                    element = self.driver.find_element(By.TAG_NAME,value)
                    log.debug('元素定位成功。定位方式：%s,使用的值：%s' % (by, value), tid)
                elif by == 'link':
                    element = self.driver.find_element(By.LINK_TEXT,value)
                    log.debug('元素定位成功。定位方式：%s,使用的值：%s' % (by, value), tid)
                elif by == 'plink':
                    element = self.driver.find_element(By.PARTIAL_LINK_TEXT,value)
                    log.debug('元素定位成功。定位方式：%s,使用的值：%s' % (by, value), tid)
                elif by == 'css':
                    element = self.driver.find_element(By.CSS_SELECTOR,value)
                    log.debug('元素定位成功。定位方式：%s,使用的值：%s' % (by, value), tid)
                elif by == 'xpath':
                    element = self.driver.find_element(By.XPATH,value)
                    log.debug('元素定位成功。定位方式：%s,使用的值：%s' % (by, value), tid)
                else:
                    log.error('没有找到输入的定位方式', tid)
                return element
            #输入的元素的值有误
            except NoSuchElementException as e:
                log.error("报错信息：{}".format(e), tid)
                return element
        #输入的定位方式有误就报错
        else:
            log.error('输入的元素定位方式错误,参考[id, name, class, tag, link, plink, css,xpath]', tid)

    def type(self,by,value,text, tid):
        """输入内容"""
        element = self.find_element(by,value, tid)
        try:
            element.send_keys(text)
            log.info('输入的内容：%s' % text, tid)
        except :
            try:
                self.Sleep(1)
                element.send_keys(text)
                log.info('输入的内容：%s' % text, tid)
            except BaseException as e:
                log.error('内容输入报错{}'.format(e), tid)
                raise
            #self.get_img()
            raise

    def click(self, by, value, tid):
        """点击元素"""
        element = self.find_element(by, value, tid)
        # noinspection PyBroadException
        try:
            element.click()
            log.info('点击元素成功', tid)
        except Exception as e:
            display = self.isdisplayed(element, tid)
            if display is True:
                self.Sleep(3)
                element.click()
                log.info('点击元素成功', tid)
            else:
                log.error('点击元素失败{}'.format(e), tid)
                raise


    def get_text(self,element, tid):
        """获取元素文本信息"""
        try:
            text = element.text
            log.info('获取元素{}的文本信息为：{}'.format(element, text), tid)
            return text
        except Exception as e:
            log.error('获取元素{}的文本信息错误,{}'.format(element, e), tid)

    def quit_browser(self, tid):
        """关闭浏览器"""
        self.driver.quit()
        log.info('关闭浏览器', tid)



    def jsclick(self,by, value, tid):
        element = self.element_wait(by, value, tid)
        try:
            self.driver.execute_script('arguments[0].click();', element)
            log.info('JS点击元素成功', tid)
        except BaseException as e:
            display = self.isdisplayed(element, tid)
            if display is True:
                self.Sleep(3)
                try:
                    self.driver.execute_script('arguments[0].click();', element)
                    log.info('JS点击元素成功', tid)
                except BaseException as e:
                    log.error('JS点击元素报错{}'.format(e), tid)

    def element_wait(self, by,value ,tid ,seconds=20):
        """显性等待"""
        messages = '元素: {0} 没有找到 ：在{1}S内.'.format((by, value), seconds)
        try:
            if by == "id":
                element =WebDriverWait(self.driver, seconds,1).until(EC.presence_of_element_located((By.ID, value)), messages)
            elif by == "name":
                element =WebDriverWait(self.driver, seconds,1).until(EC.presence_of_element_located((By.NAME, value)), messages)
            elif by == "class":
                element =WebDriverWait(self.driver, seconds,1).until(EC.presence_of_element_located((By.CLASS_NAME, value)),
                                                             messages)
            elif by == "link_text":
                element =WebDriverWait(self.driver, seconds,1).until(EC.presence_of_element_located((By.LINK_TEXT, value)),
                                                             messages)
            elif by == "xpath":
                element =WebDriverWait(self.driver, seconds,1).until(EC.presence_of_element_located((By.XPATH, value)),
                                                             messages)
            elif by == "css":
                element =WebDriverWait(self.driver, seconds,1).until(EC.presence_of_element_located((By.CSS_SELECTOR, value)),
                                                             messages)
            else:
                raise NameError(
                    "请检查输入是否正确！!>>'id','name','class','link_text','xpaht','css'.")
            return element
        except:
            log.error(messages, tid)
            return None
    """显性等待点击"""
    def xclick(self, by, value, tid):
        try:
            self.element_wait(by,value, tid).click()
            log.info('显性等待点击元素成功', tid)
        except:
            log.error('显性等待点击元素失败', tid)
            raise

    def Get(self, url):
        self.driver.get(url)

    def jsText(self, by, value, text, js, tid):
        try:
            element = self.element_wait(by, value, tid)
            # self.driver.execute_script("arguments[0].innerHTML = arguments[1].replace(/\\n/g, '<br>');", element, text)
            self.driver.execute_script(js, element, text)
            self.driver.execute_script("var evt = new Event('input', { bubbles: true }); arguments[0].dispatchEvent(evt);",
                                  element)

            log.info(f"使用js输入文本成功{text}", tid)
        except BaseException as e:
            log.error(f'使用js输入文本失败{e}', tid)

